package com.eflying.common.utils;

import java.text.MessageFormat;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import com.eflying.user.bean.User;

public class JavaMail {

	public void send(User user) throws Exception {
		
		Properties props = new Properties();
		props.load(this.getClass().getClassLoader().getResourceAsStream("email_template.properties"));
		//配置对话必须认证
		props.setProperty("mail.smtp.auth", "true");
		//选择传输协议
		props.setProperty("mail.transport.protocol", "smtp");
		/*
		 * 邮件环境
		 */
		Session session = Session.getInstance(props);
		//我要看调试信息（发布时可去除）
		session.setDebug(true);
		/*
		 * 1.首先创建一个邮件对象
		 */
		Message msg = null;
		msg = new MimeMessage(session);
		
		msg.setSubject("来自Asura书城的测试邮件！");
		String content = MessageFormat.format(props.getProperty("content"),user.getActivationCode());
		msg.setContent(
				content,"text/html;charset=UTF-8"
				);
		//mail.from需要用Address对象
		Address address = new InternetAddress(MimeUtility.encodeText("Asura书城")+" <ping3008@sina.com>");
		msg.setFrom(address);
		/*
		 * 2.创建一个运输车
		 */
		Transport transport = null;
		transport = session.getTransport();
		String host = "smtp.sina.com";
		String fromUser = "ping3008";
		String password = "ss82180750";
		transport.connect(host, fromUser, password);
		/*
		 * 3.让运输车去送电子邮件
		 */
		transport.sendMessage(msg,new Address[]{new InternetAddress(user.getEmail())});
		
		transport.close();
	}
}
